#!/usr/bin/env bash
set -exu

check_installer() {
  if [ -e /etc/NIXOS ]; then
    echo -e "\e[1;32mRunning in the NixOS installer environment.\e[0m"
  else
    echo -e "\e[1;31mNot running in the NixOS installer environment.\e[0m"
    exit 1
  fi
}

cleanup() {
  rm -rf nixos-config-main.zip nixos-config-main nixos-config
}

download_config() {
  curl -LJ0 https://github.com/dustinlyons/nixos-config/archive/main.zip -o nixos-config-main.zip
  unzip nixos-config-main.zip
  mv nixos-config-main/templates/starter nixos-config
  cd nixos-config
}

run_apply() {
  ./apps/x86_64-linux/apply
  if [ ! -f /tmp/username.txt ]; then
    echo -e "\e[1;31mError: /tmp/username.txt does not exist.\e[0m"
    exit 1
  fi
  export USERNAME=$(cat /tmp/username.txt)
}

run_disko() {
  sudo nix run --extra-experimental-features nix-command --extra-experimental-features flakes \
    github:nix-community/disko -- --mode zap_create_mount ./modules/nixos/disk-config.nix
}

setup_files() {
  sudo mkdir -p /mnt/etc/nixos
  sudo cp -r * /mnt/etc/nixos
  cd /mnt/etc/nixos
}

install_nixos() {
  ARCH=$(uname -m)

  case "$ARCH" in
    x86_64)
      FLAKE_TARGET="x86_64-linux"
      ;;
    aarch64)
      FLAKE_TARGET="aarch64-linux"
      ;;
    *)
      echo -e "${RED}Unsupported architecture: $ARCH${CLEAR}"
      exit 1
      ;;
  esac

  sudo nixos-install --flake .#$FLAKE_TARGET $@
  sudo chmod -R 775 /mnt/etc/nixos
}

prompt_reboot() {
  read -p "Do you want to reboot now? (y/yes) " choice
  case "$choice" in
  y|Y|yes|YES ) echo -e "\e[1;32mRebooting...\e[0m" && sudo reboot;;
  * ) echo -e "\e[1;33mReboot skipped.\e[0m";;
  esac
}

cleanup
check_installer
download_config
run_apply
run_disko
setup_files
install_nixos
cleanup
prompt_reboot
